package com.css.fxfzfxqh.modules.reportmanagement.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.common.utils.DateUtils;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.CalculationTasks;
import com.css.fxfzfxqh.modules.reportmanagement.repository.BuildingDataRepository;
import com.css.fxfzfxqh.modules.reportmanagement.service.*;
import com.css.fxfzfxqh.modules.reportmanagement.vo.BuildingVO;
import com.css.fxfzfxqh.modules.reportmanagement.vo.CalculationTasksVO;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ReportDataServiceImpl implements ReportDataService {
    private static final Logger logger = LoggerFactory.getLogger(ReportDataServiceImpl.class);
    @Autowired
    PgbgZdryqkReportService pgbgZdryqkReportService;
    @Autowired
    ExportPGReportDataService exportPGReportDataService;
    @Autowired
    ExportReportDataService exportReportDataService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    BuildingDataRepository buildingDataRepository;
    @Resource
    SUserService sUserService;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void updateTaskReportData(String dataId, String final_report_file_id, String final_report_file_name) {
        try{
            String updateSql="update fxqh_calculation_tasks_report set final_report_file_id=? ,final_report_file_name=? ,create_user=?,create_time=CAST (? AS timestamp) where id=?";
            String user = sUserService.getSUser(PlatformSessionContext.getUserID());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            Date date = new Date();
            String createTime = DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
            int count = jdbcTemplate.update(updateSql,final_report_file_id,final_report_file_name,sUser.getUserName(),createTime,dataId);
            logger.info("updateTaskReportData方法更新执行sql:{},参数:{},{},{},{},{}",updateSql,final_report_file_id,final_report_file_name,sUser.getUserName(),createTime,dataId);
        }catch (Exception e){
            logger.error("updateTaskReportData方法更新执行sql更新失败");
        }

    }

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, CalculationTasksVO param) {
        Integer total =0;
        List<CalculationTasksVO> list = new ArrayList<>();
        if(PlatformObjectUtils.isEmpty(param.getPglb())){
            param.setPglb("建筑物评估");
        }
        //建筑物评估查询
        if("jzwpg".equals(param.getPglb()) || "建筑物评估".equals(param.getPglb())){
            int firstIndex = (curPage - 1) * pageSize;
            int lastIndex = pageSize;
            StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
            StringBuilder sql = new StringBuilder(" ");
            sql.append("select * from (                                                                             ");
            sql.append("SELECT '建筑物评估' as pglb, t1.*,t2.pp_name as province_name,t2.city_name  ,t2.NAME as county_name,              ");
            sql.append("pid as province_id,t2.cid as city_id,t2.id as county_id  FROM fxqh_calculation_tasks t1     ");
            sql.append("LEFT JOIN fxqh_assess_toponym t2 ON t1.ID=t2.assess_id                                      ");
            sql.append(") t1 WHERE 1=1                                                                               ");

            if (!PlatformObjectUtils.isEmpty(param.getAssessName())) {
                sql.append(" and t1.assess_name like '%" + param.getAssessName() + "%'");
            }
            if (!PlatformObjectUtils.isEmpty(param.getAssessCode())) {
                sql.append(" and t1.assess_code like '%" + param.getAssessCode() + "%'");
            }

            if (!PlatformObjectUtils.isEmpty(param.getAssessType())) {
                sql.append(" and t1.assess_type = '" + param.getAssessType() + "'");
            }

            if (!PlatformObjectUtils.isEmpty(param.getProvinceName())) {
                sql.append(" and t1.province_id = '" + param.getProvinceName() + "'");
            }
            if (!PlatformObjectUtils.isEmpty(param.getCityName())) {
                sql.append(" and t1.city_id = '" + param.getCityName() + "'");
            }
            if (!PlatformObjectUtils.isEmpty(param.getCountyName())) {
                sql.append(" and t1.county_id = '" + param.getCountyName() + "'");
            }

            if (!PlatformObjectUtils.isEmpty(param.getTaskRange())) {
                sql.append(" and t1.task_range = '" + param.getTaskRange() + "'");
            }
            StringBuilder orderSql = new StringBuilder(" order by create_time desc");
            total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(CalculationTasksVO.class)).size();
            list = jdbcTemplate.query(sql.append(orderSql).append(limitSql).toString(), new BeanPropertyRowMapper<>(CalculationTasksVO.class));

        }
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public Map<String, Object> getPage1(int curPage, int pageSize, BuildingVO param) {
        param.setRole(getRole());
        return buildingDataRepository.getAll(param, curPage, pageSize);
    }
    private String getRole() {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE))
            return "0";
        if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE))
            return "1";
        if (allRole.contains(FxfzConstants.PH_CITY_CODE))
            return "2";
        if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE))
            return "3";
        return "3";
    }

    @Override
    public List<Map<String, Object>> getTaskReportList(String taskId) {
        StringBuilder sb = new StringBuilder("select count(*)  as num from fxqh_calculation_tasks_report where task_id=?");
//        String taskId ="4fb1f14bfb144154b45eebde98743de3";
        Map<String,Object> countMap = jdbcTemplate.queryForMap(sb.toString(),taskId);
        Integer count = Integer.parseInt(countMap.get("num").toString());
        if(count==0){
            //初始化报告数据
            insertTaskReqortData(taskId);
        }
        //String sql ="select * from  fxqh_calculation_tasks_report where task_id=? ";
        StringBuilder sbSQL = new StringBuilder();
        sbSQL.append("select t.id," +
                "t.task_id," +
                "t.type_name," +
                "t.report_file_id," +
                "t.report_file_name," +
                "t.final_report_file_id," +
                "t.final_report_file_name," +
                "t.create_user," +
                "t.type_id," +
                "to_char(t.create_time, 'YYYY-MM-DD HH24:mm:ss') as create_time," +
                "t.create_user_id,case when t.type_id ='0' then COALESCE(t2.structural_ld_progress,'0')          ");
        sbSQL.append("	when t.type_id ='1' then COALESCE(t2.structural_four_progress,'0')        ");
        sbSQL.append("	when t.type_id ='2' then COALESCE(t2.structural_occurrence_progress,'0')    ");
        sbSQL.append("	when t.type_id ='3' then COALESCE(t2.structural_go_beyond_progress,'0')      ");
        sbSQL.append("	end as status                                                                     ");
        sbSQL.append("from  fxqh_calculation_tasks_report t                                               ");
        sbSQL.append("left join fxqh_calculation_tasks t2 on t.task_id=t2.id                              ");
        sbSQL.append("where task_id= ?                                  ");

        List<Map<String,Object>> list = jdbcTemplate.queryForList(sbSQL.toString(),taskId);
        return list;
    }

    @Override
    public Map<String, Object> getTaskObj(String taskId) {
        String sql ="select * from  fxqh_calculation_tasks where id=? ";
        Map<String,Object> map = jdbcTemplate.queryForMap(sql,taskId);
        return map;
    }

    private void insertTaskReqortData(String taskId){
        String sql = "select * from fxqh_calculation_tasks where id='%s'";
        sql = String.format(sql,taskId);
        CalculationTasks task = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(CalculationTasks.class));
        if(task!=null){
            String seismicInputMode= task.getSeismicInputMode();
            String[] inputModeArray= seismicInputMode.split(",");

            String insertSql = "insert into fxqh_calculation_tasks_report(id,task_id,type_id,type_name) values(?,?,?,?) ";
            List<Object[]> args = new ArrayList<>();
            for(int i=0;i<inputModeArray.length;i++){
                String id =UUIDGenerator.getUUID();
                //地震输入方式0为设定烈度1为四个概率,2为地震影响场,  3为发生概率危险性,4为超越概率危险性,多个数字之间用,分隔
                String typeName="设定烈度";
                if("1".equals(inputModeArray[i])){
                    typeName="四个概率";
                } if("2".equals(inputModeArray[i])){
                    typeName="地震影响场";
                } if("3".equals(inputModeArray[i])){
                    typeName="发生概率危险性";
                }if("4".equals(inputModeArray[i])){
                    typeName="超越概率危险性";
                }
                args.add(new Object[]{id,taskId,inputModeArray[i],typeName});
            }
            if(!args.isEmpty()){
                int[] batchUpdateCount = jdbcTemplate.batchUpdate(insertSql, args);
                logger.info("批量新增个数：" + Arrays.toString(batchUpdateCount));
            }
        }
    }

}
